package com.tubemostwanted.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import net.sf.json.JSONObject;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.tubemostwanted.entity.Category;
import com.tubemostwanted.entity.Tube;
import com.tubemostwanted.model.CategoryModel;
import com.tubemostwanted.model.TubeModel;
import com.tubemostwanted.service.TubeService;
import com.tubemostwanted.util.StringHelper;

@SuppressWarnings("serial")
public class AdCategoryController extends HttpServlet {

	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	@SuppressWarnings("unused")
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String path = ((HttpServletRequest) request).getRequestURI();
		String action = "";
		String[] splittedURI = path.split("/");
		// if length = 3, this is for action request.
		if (splittedURI.length == 4) {
			action = splittedURI[splittedURI.length - 1];
			System.out.println("Do action : " + action);
			// create new category, return create page.
			if (action.equalsIgnoreCase("manager")) {
				List<Category> result = CategoryModel.all();
				if (result != null && result.size() > 0) {
					request.setAttribute("result", result);
					request.getRequestDispatcher("/category_manager.jsp")
							.forward(request, response);
				} else {
					response.getWriter()
							.println("Category table have no item.");
				}
			} else if (action.equalsIgnoreCase("all")) {
				System.out.println("Ok");
				if (request.getParameter("categoryAlias") != null) {
					int page = 1;
					if (request.getParameter("page") != null) {
						page = Integer.parseInt(request.getParameter("page"));
					}
					Category cate = CategoryModel.getByCateAlias(request
							.getParameter("categoryAlias"));
					System.out.println("Ok 2");
					if (cate != null) {
						System.out.println(cate.getTitle().getValue());
						if (cate != null) {
							JSONObject object = new JSONObject();
							object.put("categoryAlias", cate.getAlias());
							object.put("thumbImageUrl", cate.getThumbImageUrl()
									.getValue());
							object.put("count", cate.getCount());
							object.put("subTitle", cate.getSubTitle());
							object.put("description", cate.getDescription()
									.getValue());
							object.put("listTube", TubeModel.getByCategory(
									cate.getAlias(), page, 10));
							System.out.println("Get all ok, Category : "
									+ cate.getAlias() + ", page : " + page);
							response.getWriter().write(object.toString());
						}
					}
				}
			}
			// view category.
			else if (action.equalsIgnoreCase("view")) {
				Category cate = CategoryModel.getByCateAlias(request
						.getParameter("alias"));
				if (cate != null) {
					List<Tube> result = TubeModel.getAllByCategory(cate
							.getAlias());
					if (result.size() > 0) {
						request.setAttribute("result", result);
						request.setAttribute("cate", cate);
						request.getRequestDispatcher("/category_view.jsp")
								.forward(request, response);
					}
				} else {

				}

			}
			// create category.
			else if (action.equalsIgnoreCase("create")) {
				request.getRequestDispatcher("/category_create.jsp").forward(
						request, response);
			}
			// edit category.
			else if (action.equalsIgnoreCase("edit")) {
				response.getWriter().println("Edit.");
			}
			// delete category.
			else if (action.equalsIgnoreCase("delete")) {
				String id = request.getParameter("id");
				if (id != null) {
					Category cate = CategoryModel.getByCateAlias(id);
					if (cate != null) {
						cate.setStatus(4);
						CategoryModel.update(cate);
						CategoryModel.closePM();
						List<Tube> listTube = TubeModel.getAllByCategory(cate
								.getAlias());
						for (Tube tube : listTube) {
							tube = TubeModel.getByTubeId(tube.getTubeId());
							tube.setCategoryAlias("");
							TubeModel.update(tube);
						}
						TubeModel.closePM();
						response.sendRedirect("/admin/category/manager");
					} else {
						response.getWriter().println("Category is not exits.");
					}

				} else {
					response.getWriter().println(
							"Invalid category. Please try again.");
				}
			}// edit list clips in category.
			else if (action.equalsIgnoreCase("edit_videos")) {
				Category cate = CategoryModel.getByCateAlias(request
						.getParameter("id"));
				if (cate != null) {
					List<Tube> listTube = TubeModel.getAllByCategory(cate
							.getAlias());
					request.setAttribute("result", listTube);
					request.setAttribute("cate", cate);
					request.getRequestDispatcher("/category_edit_videos.jsp")
							.forward(request, response);
				} else {
					response.getWriter().println("Category is not exits.");
				}
			}
			// add clips to category.
			else if (action.equalsIgnoreCase("add_video")) {
				if (request.getParameter("nextId") == null
						&& request.getParameter("prevId") == null) {
					Category cate = CategoryModel.getByCateAlias(request
							.getParameter("categoryAlias"));
					Tube tub = TubeModel.getByTubeId(request
							.getParameter("tubeId"));
					if (tub == null) {
						tub = TubeService.searchById(
								request.getParameter("tubeId"), true);
					}
					if (tub.getCategoryAlias() != null
							&& tub.getCategoryAlias().equalsIgnoreCase(
									cate.getAlias())) {

					} else {
						cate.setCount(cate.getCount() + 1);
					}
					tub.setCategoryAlias(cate.getAlias());
					tub.setCategoryIndex(1000000);
					TubeModel.update(tub);
					CategoryModel.update(cate);
					TubeModel.closePM();
					CategoryModel.closePM();
				} else if (request.getParameter("prevId") == null) {
					Category cate = CategoryModel.getByCateAlias(request
							.getParameter("categoryAlias"));
					Tube tub = TubeModel.getByTubeId(request
							.getParameter("tubeId"));
					if (tub == null) {
						tub = TubeService.searchById(
								request.getParameter("tubeId"), true);
					}
					if (tub.getCategoryAlias() != null
							&& tub.getCategoryAlias().equalsIgnoreCase(
									cate.getAlias())) {

					} else {
						cate.setCount(cate.getCount() + 1);
					}
					Tube nextTub = TubeModel.getByTubeId(request
							.getParameter("nextId"));
					tub.setCategoryAlias(cate.getAlias());
					tub.setCategoryIndex(nextTub.getCategoryIndex() / 2);
					TubeModel.update(tub);
					CategoryModel.update(cate);
					TubeModel.closePM();
					CategoryModel.closePM();
				} else if (request.getParameter("nextId") == null) {
					Category cate = CategoryModel.getByCateAlias(request
							.getParameter("categoryAlias"));
					Tube tub = TubeModel.getByTubeId(request
							.getParameter("tubeId"));
					if (tub == null) {
						tub = TubeService.searchById(
								request.getParameter("tubeId"), true);
					}
					if (tub.getCategoryAlias() != null
							&& tub.getCategoryAlias().equalsIgnoreCase(
									cate.getAlias())) {
					} else {
						cate.setCount(cate.getCount() + 1);
					}
					Tube prevTub = TubeModel.getByTubeId(request
							.getParameter("prevId"));
					tub.setCategoryAlias(cate.getAlias());
					tub.setCategoryIndex(prevTub.getCategoryIndex() + 1000000);
					TubeModel.update(tub);
					CategoryModel.update(cate);
					TubeModel.closePM();
					CategoryModel.closePM();
				} else {
					Category cate = CategoryModel.getByCateAlias(request
							.getParameter("categoryAlias"));
					Tube tub = TubeModel.getByTubeId(request
							.getParameter("tubeId"));
					if (tub == null) {
						tub = TubeService.searchById(
								request.getParameter("tubeId"), true);
					}
					if (tub.getCategoryAlias() != null
							&& tub.getCategoryAlias().equalsIgnoreCase(
									cate.getAlias())) {

					} else {
						cate.setCount(cate.getCount() + 1);
					}
					Tube nextTub = TubeModel.getByTubeId(request
							.getParameter("nextId"));
					Tube prevTub = TubeModel.getByTubeId(request
							.getParameter("prevId"));
					tub.setCategoryAlias(cate.getAlias());
					// calculate tub position.
					tub.setCategoryIndex((nextTub.getCategoryIndex() + prevTub
							.getCategoryIndex()) / 2);
					System.out.println(tub.getTitle().getValue()
							+ " was added to category : "
							+ cate.getTitle().getValue() + " between "
							+ prevTub.getTitle().getValue() + " and "
							+ nextTub.getTitle().getValue());
					CategoryModel.update(cate);
					TubeModel.update(tub);
					CategoryModel.closePM();
					TubeModel.closePM();
				}
				response.getWriter().println(
						"<div><p style='color:green'>Update success</p></div>");
			}

			// reorder category index
			else if (action.equalsIgnoreCase("re_order_index")) {
				if (request.getParameter("prevAlias") == null
						&& request.getParameter("nextAlias") == null) {
					Category current = CategoryModel.getByCateAlias(request
							.getParameter("currentAlias"));
					current.setIndex(1000000);
					CategoryModel.update(current);
					CategoryModel.closePM();
				} else if (request.getParameter("prevAlias") == null) {
					Category current = CategoryModel.getByCateAlias(request
							.getParameter("currentAlias"));
					Category next = CategoryModel.getByCateAlias(request
							.getParameter("nextAlias"));
					current.setIndex(next.getIndex() / 2);
					CategoryModel.update(current);
					CategoryModel.closePM();

				} else if (request.getParameter("nextAlias") == null) {
					Category current = CategoryModel.getByCateAlias(request
							.getParameter("currentAlias"));
					Category pre = CategoryModel.getByCateAlias(request
							.getParameter("prevAlias"));
					current.setIndex(pre.getIndex() + 1000000);
					CategoryModel.update(current);
					CategoryModel.closePM();
				} else {
					Category current = CategoryModel.getByCateAlias(request
							.getParameter("currentAlias"));
					Category pre = CategoryModel.getByCateAlias(request
							.getParameter("prevAlias"));
					Category next = CategoryModel.getByCateAlias(request
							.getParameter("nextAlias"));
					current.setIndex((pre.getIndex() + next.getIndex()) / 2);
					CategoryModel.update(current);
					CategoryModel.closePM();
				}
				response.getWriter().println(
						"<div><p style='color:green'>Update success</p></div>");
			}

			// remove clips from category.
			else if (action.equalsIgnoreCase("remove_video")) {
				Tube tub = TubeModel
						.getByTubeId(request.getParameter("tubeId"));
				Category cate = CategoryModel.getByCateAlias(request
						.getParameter("categoryAlias"));
				if (cate.getCount() > 0) {
					cate.setCount(cate.getCount() - 1);
				}
				CategoryModel.update(cate);
				CategoryModel.closePM();
				tub.setCategoryAlias("");
				TubeModel.update(tub);
				TubeModel.closePM();
				response.getWriter()
						.println(
								"<div><p style='color:green'>Video removed success !</p></div>");
			}
		}
		// if length = 4, this is view detail playlist request.
		else if (splittedURI.length == 5) {
			response.getWriter().println("Length = 5.");
		}
	}

	@SuppressWarnings("unused")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=UTF-8");
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		// if (user != null) {
		String action = req.getParameter("action");
		if (action.equalsIgnoreCase("create")) {
			Category cate = new Category();
			if (req.getParameter("title") != null) {
				cate.setTitle(new Text(req.getParameter("title")));
			}
			if (req.getParameter("description") != null) {
				cate.setDescription(new Text(req.getParameter("description")));
			}
			Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
			List<BlobKey> blobKeys = blobs.get("myFile");
			if (blobKeys != null && blobKeys.size() > 0) {
				cate.setThumbImageUrl(new Text("/image?key="
						+ blobKeys.get(0).getKeyString()));
			}
			cate.setCount(0);
			cate.setStatus(1);
			cate.setAlias(StringHelper.getAliasByLanguage(cate.getTitle()
					.getValue()));
			cate.setIndex(CategoryModel.getMaxIndex() + 1000000);
			CategoryModel.add(cate);
			resp.sendRedirect("/admin/category/manager");

		} else if (action.equalsIgnoreCase("addVideo")) {
			if (req.getParameter("categoryAlias") != null
					&& req.getParameter("tubeId") != null) {
				Category cate = CategoryModel.getByCateAlias(req
						.getParameter("categoryAlias"));
				Tube detail = TubeModel.getByTubeId(req.getParameter("tubeId"));
				if (detail == null) {
					detail = TubeService.searchById(req.getParameter("tubeId"),
							true);
				}
				if (detail != null && cate != null) {
					cate.setCount(cate.getCount() + 1);
					CategoryModel.update(cate);
					CategoryModel.closePM();
					detail.setCategoryAlias(cate.getAlias());
					TubeModel.add(detail);
				}
			}
		}
		// } else {
		// System.out.println("User is not login.");
		// resp.sendRedirect("/login");
		// }
	}
}
